package com.example.pingtools.util

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.IOException
import java.lang.Exception
import java.net.ConnectException
import java.net.InetSocketAddress
import java.net.Socket

public class PingUtil {
    public  fun startPing(ip: String): Boolean {
        Log.e("Ping", "startPing...$ip")
        var success = false
        var p: Process? = null
        try {
            p = Runtime.getRuntime().exec("ping -c 4 -i 0.2 -W 1 $ip")
            val status = p.waitFor()
            success = if (status == 0) {
                true
            } else {
                false
            }
        } catch (e: IOException) {
            success = false
        } catch (e: InterruptedException) {
            success = false
        } finally {
            p!!.destroy()
        }
        return success
    }



    fun isHostConnectable(host: String?, port: Int): Boolean {
        var isopen:Boolean=false
        GlobalScope.launch(Dispatchers.Default) {
           /* for (i in 10 downTo 1) {
                tv.text = "$i"
                delay(1000)
            }
            tv.text = "Done!"*/
            val socket = Socket()
            try {
                socket.connect(InetSocketAddress(host, port))
            } catch (e: IOException) {
                e.printStackTrace()
                isopen= false
            } finally {
                try {
                    socket.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
           isopen= true
        }
        return isopen

    }
}